<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Shopping Cart Example</title>
</head>

<body>
    <div id="app">
        <button @click="clk">添加商品</button>
        <qd-store :items="list" @mont="monts"><template v-slot:item-details="{item}">
                <span style="margin: 0 5px;">商品：{{item.name}}，数量：{{item.quantity}}</span>
            </template></qd-store>
    </div>
</body>
<script src="./vue.js"></script>
<script>
    const { createApp, ref, computed } = Vue;
    const app = createApp({
        setup() {
            let list = ref([
                { name: '苹果', quantity: 0 },
                { name: '香蕉', quantity: 0 },
                { name: '橙子', quantity: 0 }
            ])

            function monts(newItems) {
                list.value = newItems;
            }
            function clk() {
                const abc = list.value.map(item => {
                    return { ...item, quantity: item.quantity + 1 }
                })
                monts(abc)
            }

            return {
                list,
                monts,
                clk
            }
        }
    })

    app.component('qd-store', {
        props: ['items'],
        setup(props, { emit }) {
            let showA = computed(() => props.items);
            function add(index) {
                const abc = showA.value.map((item, i) => {
                    if (i === index) {
                        return { ...item, quantity: item.quantity > 0 ? item.quantity - 1 : 0 }
                    }
                    return item;
                })
                emit('mont', abc)
            }
            function abb(index) {
                const abc = showA.value.map((item, i) => {
                    if (i === index) {
                        return { ...item, quantity: item.quantity + 1 };
                    }
                    return item;
                })
                emit('mont', abc);
            }

            return {
                showA,
                add,
                abb
            }
        },
        template: `
                    <div v-for="(item, index) in showA" :key="index">
                        <button @click="add(index)">-</button>
                        <span>{{item.quantity}}</span>
                        <button @click="abb(index)">+</button>
                        <slot name="item-details" :item="item" />
                        </div>        
                      `
    }).mount('#app')
</script>

</html>